var cf = require("../../../config.js");
var cf2 = require("../../../utils/config2");
var util = require("../../../utils/util.js");
var cusmallToken = wx.getStorageSync('cusmallToken');
var baseHandle = require("../../template/baseHandle.js");
//获取应用实例
var app = getApp();
const recorderManager = wx.getRecorderManager()
const innerAudioContext = wx.createInnerAudioContext();
var vTimer = null;
var webim = global.webim;
Page(Object.assign({}, baseHandle, {

  /**
   * 页面的初始数据
   */
  data: {
    extConfig: wx.getExtConfigSync ? wx.getExtConfigSync() : {},
    app: app,
    cardInfo: {},
    companyMsg: {},
    submitInfo: {},
    staticResPath: cf.config.staticResPath,
    userImagePath: cf.config.userImagePath,
    min: 5, //最少字数
    max: 500,

    recorderManager: null,
    innerAudioContext: null,
    playing: false,
    recordStatus: 0, //0 等待录音 1 录音中 2 录音结束 3 播放临时录音
    tempSound: null,
    maxSeconds: 60,
    showVoiceModal: false,
    soundTime: "00",

    uploadImgList: [],
    region: ['', '', ''],
    headImg: "",
    locationInfo: {},
    cardStyleId: 0,
    qiniuDomain: "",
    videoUrl: "",
    videoImg: "",
    customStyle: "",
    defCustStyleIco: cf.config.staticResPath + "/mobile/image/cust_card_ico.png",
    uploadParams: {},
    myImg: [],
    emProduct: [],
    productValue: '',
    productLabel: '',
    textAreaValue: ''
  },
  // 获取楼盘列表
  // getHouse(phone) {
  //   const that = this
  //   wx.request({
  //     url: `${cf2.default.dataCenter}/zmzj/product/${phone}/1/999`,
  //     data: {},
  //     header: {
  //       'content-type': 'application/json',
  //       'token': wx.getStorageSync('authName')
  //     },
  //     success: function (res) {
  //       let arr = [];
  //       if (res.data.data && res.data.data.list) {
  //         arr = res.data.data.list.map(item => {
  //           return { value: item.projectId, label: item.name }
  //         })
  //       }
  //       that.setData({ emProduct: arr })
  //       // console.log(res)
  //     }
  //   })
  // },
  //主推楼盘数据切换
  productChange(e) {
    let that = this
    console.log(e.detail.value)
    this.setData({
      productValue: that.data.emProduct[e.detail.value].value,
      productLabel: that.data.emProduct[e.detail.value].label
    })
  },
  //获取名片信息
  getCardInfo() {
    var ctx = this;
    wx.showLoading({
      title: '加载中',
    });
    wx.request({
      url: cf.config.pageDomain + '/applet/mobile/visitcard/employee/getEmployeeInfo',
      data: {
        cusmallToken: cusmallToken,
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        var data = res.data;
        if (data && data.ret == 0) {
          if (data.model.employee.showPic) {
            data.model.employee.showPic = data.model.employee.showPic.split(",");
          } else {
            data.model.employee.showPic = [];
          }
          if (data.model.employee.extend) {
            data.model.employee.extend = JSON.parse(data.model.employee.extend)
            var resData = data.model.employee.extend;
            if (resData.region) {
              ctx.setData({
                region: resData.region.split(',')
              })
            }
            if (resData.telephone) {
              ctx.setData({
                ['submitInfo.telephone']: resData.telephone
              })
            }
            if (resData.address) {
              ctx.setData({
                ['submitInfo.address']: resData.address || ctx.data.companyMsg.location
              })
            }
            if (resData.locationInfo) {
              ctx.setData({
                locationInfo: resData.locationInfo
              })
            }
          }
          if (data.model.employee.personalProfile) {
            ctx.setData({
              currentWordNumber: parseInt(data.model.employee.personalProfile.length)
            })
          }
          if (data.model.employee.voiceUrl) {
            ctx.setData({
              voiceFile: data.model.employee.voiceUrl
            })
          }
          if (data.model.employee.voiceTime) {
            ctx.setData({
              soundTime: data.model.employee.voiceTime
            })
          }
          if (data.model.employee.phone) {
            ctx.setData({
              ['submitInfo.phone']: data.model.employee.phone
            })
            // ctx.getHouse(data.model.employee.phone)
          }
          if (data.model.employee.wxAccount) {
            ctx.setData({
              ['submitInfo.wxAccount']: data.model.employee.wxAccount || ""
            })
          }
          if (data.model.employee.email) {
            ctx.setData({
              ['submitInfo.email']: data.model.employee.email
            })
          }
          if (data.model.employee.projectId) {
            ctx.setData({
              productValue: data.model.employee.projectId,
              productLabel: data.model.employee.salesProductName
            })
          }
          if (data.model.employee.post) {
            ctx.setData({
              ['submitInfo.post']: data.model.employee.post
            })
          }
          if (data.model.employee.company) {
            ctx.setData({
              ['submitInfo.company']: data.model.employee.company
            })
          }
          if (data.model.employee.personalProfile) {
            ctx.setData({
              ['submitInfo.personalProfile']: data.model.employee.personalProfile
            })
          }
          if ("" != data.model.employee.labels) {
            data.model.employee.labels = JSON.parse(data.model.employee.labels);
          } else {
            data.model.employee.labels = [];
          }
          // debugger
          var projectInfo = []
          if (data.model.employee.projectInfo){
            projectInfo = JSON.parse(data.model.employee.projectInfo)
          }
          console.log(projectInfo)
          let arr = projectInfo.map((item,index)=>{
            return  { value: item.projectId, label: item.projectName }
          })
          
          ctx.setData({
            cardInfo: data.model.employee,
            customStyle: data.model.employee.customStyle || "",
            videoUrl: data.model.employee.videoUrl || "",
            videoImg: data.model.employee.videoImg || "",
            headImg: data.model.employee.headPic,
            cardStyleId: data.model.employee.cardStyleId == undefined ? 0 : data.model.employee.cardStyleId,
            emProduct: arr
          });
          if (!ctx.data.myImg.length) {
            ctx.setData({
              myImg: data.model.employee.showPic,
            })
          }
        }
      },
      complete: function () {
        wx.hideLoading();
      }
    })
  },
  reGetToken() {
    let that = this;
    let promise = new Promise((resolve, reject) => {
      let now = new Date().getTime() / 1000 - 30
      if (now > Number(that.data.uploadParams.expire)) {
        wx.request({
          url: cf.config.pageDomain + '/applet/mobile/aliyunoss/getUploadToken',
          header: {
            "Content-Type": "application/json"
          },
          success: function (res) {
            that.setData({
              uploadParams: res.data.model
            })
            resolve({ policy: res.data.model.policy, signature: res.data.model.signature })
          }
        })
      } else {
        resolve({ policy: that.data.uploadParams.policy, signature: that.data.uploadParams.signature })
      }
    })
    return promise
  },
  bindRegionChange: function (e) {
    this.setData({
      region: e.detail.value
    })
  },
  bindStyleChange: function (e) {
    var idx = e.target.dataset.idx;
    this.setData({
      cardStyleId: idx
    });
  },
  inputs: function (e) {
    var ctx = this;
    ctx.data.submitInfo[e.currentTarget.id] = e.detail.value;
  },
  linkTo: function () {
    wx.navigateTo({
      url: '/pages/sales/my_shop/my_shop',
    })
  },
  inputtextarea: function (e) {
    // 获取输入框的内容
    var value = e.detail.value;
    console.log(value)
    // 获取输入框内容的长度
    var len = parseInt(value.length);
    //this.data.submitInfo[e.currentTarget.id] = value;
    this.setData({
      textAreaValue: value,
      'submitInfo.personalProfile': value
    })
    //最少字数限制
    if (len <= this.data.min)
      this.setData({
        texts: "加油，够5个字可以得20积分哦"
      })
    else if (len > this.data.min)
      this.setData({
        texts: " "
      })

    //最多字数限制
    if (len > this.data.max) return;
    // 当输入框内容的长度大于最大长度限制（max)时，终止setData()的执行
    this.setData({
      currentWordNumber: len //当前字数  
    });
  },

  handleAddImage: function (e) {
    let that = this;
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths;
        if (e.currentTarget.id == "uploadheadPic") {
          wx.navigateTo({
            url: `/pages/cropper/cropper?src=${tempFilePaths[0]}`,
            success: function (res) { },
            fail: function (res) { },
            complete: function (res) { },
          })
        } else {
          //that.upload(that, tempFilePaths, e);
          that.aliUpload(tempFilePaths, 'image', false, e)
        }
      }
    })
  },
  handleDelImg: function (e) {
    let vm = this;
    let idx = e.target.dataset.index;
    let imgList = vm.data.myImg;
    if (e.currentTarget.id == "headPic") {
      vm.setData({
        headImg: null
      })
    } else {
      imgList.splice(idx, 1);
      vm.setData({
        myImg: imgList
      })
    }
  },

  //提交数据
  submit: function () {
    // debugger
    let employee = wx.getStorageSync('employee')
    //收集用户保存名片
    app.globalData.sensors.track('1006', {
      account_id: wx.getStorageSync('userId'),
      role: employee ? '置业顾问' : '用户'
    });
    var ctx = this;
    if (!ctx.data.headImg) {
      wx.showToast({
        title: "头像不能为空",
        icon: "none"
      });
      return;
    }
    if (!ctx.data.submitInfo.phone) {
      wx.showToast({
        title: "手机号码不能为空",
        icon: "none"
      });
      return;
    }
    if (5 == ctx.data.cardStyleId && !ctx.data.customStyle) {
      wx.showToast({
        title: "请上传图片",
        icon: "none"
      });
      return;
    }
    if (!ctx.data.submitInfo.post) {
      wx.showToast({
        title: "请输入职位",
        icon: "none"
      });
      return;
    }
    // if (!ctx.data.submitInfo.company) {
    //   wx.showToast({
    //     title: "请输入公司名称",
    //     icon: "none"
    //   });
    //   return;
    // }
    if (!ctx.data.submitInfo.address) {
      ctx.data.submitInfo.address = ''
    }
    if (!ctx.data.submitInfo.telephone) {
      ctx.data.submitInfo.telephone = '';
    }
    if (!ctx.data.submitInfo.personalProfile) {
      ctx.data.submitInfo.personalProfile = '';
    }
    if (!ctx.data.submitInfo.email) {
      ctx.data.submitInfo.email = '';
    }
    //扩展信息
    var extralMsg = {
      'address': ctx.data.submitInfo.address,
      'telephone': ctx.data.submitInfo.telephone,
      'region': ctx.data.region.join(','),
      'locationInfo': ctx.data.locationInfo
    }
    // debugger
    wx.request({
      url: cf.config.pageDomain + '/applet/mobile/visitcard/employee/modifyEmployeeInfo',
      data: {
        id: ctx.data.cardInfo.id,
        cusmallToken: cusmallToken,
        phone: ctx.data.submitInfo.phone,
        telephone: ctx.data.submitInfo.telephone,
        wxAccount: ctx.data.submitInfo.wxAccount || "",
        email: ctx.data.submitInfo.email,
        company: ctx.data.submitInfo.company,
        post: ctx.data.submitInfo.post,
        personalProfile: ctx.data.submitInfo.personalProfile,
        showPic: ctx.data.myImg.join(','),
        extend: extralMsg,
        headPic: ctx.data.headImg,
        voiceUrl: ctx.data.voiceFile || "",
        voiceTime: ctx.data.soundTime || '',
        cardStyleId: ctx.data.cardStyleId,//5   是自定义图片
        videoUrl: ctx.data.videoUrl || "",
        videoImg: ctx.data.videoImg,
        customStyle: ctx.data.customStyle,
        useCustomStyle: ctx.data.cardStyleId == 5 ? true : false,
        salesProductName: ctx.data.productLabel,
        projectId: ctx.data.productValue
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        var data = res.data;
        if (data && data.ret == 0) {
          // wx.setStorageSync('updataCard', true)
          wx.setStorageSync('updataCard1', true)
          wx.setStorageSync('updataCard2', true)
          wx.showModal({
            title: '提示',
            content: '保存成功',
            showCancel: false,
            success: function (res) {
              wx.redirectTo({
                url: '/pages/sales/me/me'
              })
              // let pages = getCurrentPages();//当前页面
              // let prevPage = pages[pages.length - 2];//上一页面
              // if (prevPage.getCardInfo) {
              //   prevPage.getCardInfo();
              // }
              // wx.navigateBack({
              //   delta: 1
              // })
            }
          });
          let msg = {
            "ProfileItem": [{ "Tag": "Tag_Profile_IM_Image", "Value": ctx.data.headImg }]
          }
          webim.setProfilePortrait(msg, function (t) { console.log('修改成功') }, function (err) { console.log('修改失败') })
        } else {
          wx.showModal({
            title: '提示',
            content: '保存失败',
            showCancel: false
          })
        }
      },
      complete: function () {
        wx.hideLoading();
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var ctx = this;
    wx.hideShareMenu();
    var recorderManager = wx.getRecorderManager();
    var innerAudioContext = wx.createInnerAudioContext();
    ctx.setData({
      recorderManager: recorderManager,
      innerAudioContext: innerAudioContext,
    });
    recorderManager.onStart(ctx.soundRecordingCb);
    recorderManager.onStop(ctx.soundRecordedEndCb);
    app.getUserInfo(this, options, function (userInfo, res) {
      cusmallToken = wx.getStorageSync('cusmallToken');
      let companyMsg = wx.getStorageSync('companyInfo');
      ctx.setData({
        companyMsg: companyMsg,
        'cardInfo.company': companyMsg.shortName
      })
    });
    ctx.getCardInfo();
    //ctx.qiniuUploadToken();
    this.aliyunUploadToken();
  },


  closeVoice() {
    var ctx = this;
    ctx.resetSound();
    ctx.setData({
      showVoiceModal: false,
    });
  },
  playSound(e) {
    var ctx = this;
    var idx = e.currentTarget.dataset.idx;
    if (ctx.data.playing) {
      return;
    }
    ctx.setData({
      playing: true,
    });
    ctx.data.innerAudioContext.src = ctx.data.voiceFile;
    ctx.data.innerAudioContext.onEnded(function () {
      ctx.setData({
        playing: false,
      });
    });
    ctx.data.innerAudioContext.play();
  },
  delVoice: function () {
    var ctx = this;
    wx.showModal({
      title: '删除录音',
      content: '确定执行此操作？',
      success: function (res) {
        if (res.confirm) {
          ctx.setData({
            voiceFile: ''
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  addSound(e) {
    var ctx = this;
    ctx.setData({
      soundTime: '00',
      showVoiceModal: true,
    });
  },
  /**
   * 录音开始
   */
  soundRecording() {
    var ctx = this;
    ctx.data.recorderManager.start();
  },
  soundRecordingCb() {
    var ctx = this;
    ctx.setData({
      recordStatus: 1,
      recordStartTime: Date.now(),
    });
    var soundTime = 0;
    vTimer = setInterval(function () {
      // var soundTime = parseInt(ctx.data.soundTime)
      if (ctx.data.maxSeconds <= ctx.data.soundTime) {// 超过最大时间停止录音
        ctx.soundRecorded();
        return;
      }
      console.log(soundTime)
      soundTime++;
      soundTime = soundTime < 10 ? "0" + soundTime : soundTime; //加前置0
      ctx.setData({
        soundTime: soundTime
      });
    }, 1000);
  },
  /**
   * 录音结束
   */
  soundRecorded() {
    var ctx = this;
    ctx.data.recorderManager.stop();
  },
  soundRecordedEndCb(res) {
    var ctx = this;
    clearInterval(vTimer);
    const tempFilePath = res.tempFilePath;
    ctx.setData({
      recordStatus: 2,
      tempSound: tempFilePath
    });
    //ctx.data.recordStartTime 只有长按才会 赋值，如果没有值说明并没有长按，如果录音少于1秒也是不允许的
    if (!ctx.data.recordStartTime || (Date.now() - ctx.data.recordStartTime) < 1000) {
      ctx.resetSound();
    }
    ctx.setData({
      recordStartTime: null
    });
  },
  playTemSound() { //播放临时录制的声音
    var ctx = this;
    ctx.data.innerAudioContext.src = ctx.data.tempSound;
    ctx.data.innerAudioContext.play();
    var time = parseInt(ctx.data.soundTime) * 1000;
    ctx.data.innerAudioContext.onEnded(function () {
      ctx.setData({
        recordStatus: 2
      });
    });

    ctx.setData({
      recordStatus: 3,
    });
  },
  resetSound() { //重置声音
    var ctx = this;
    clearInterval(vTimer);
    ctx.data.innerAudioContext.stop();
    ctx.setData({
      recordStatus: 0,
      tempSound: null,
      soundTime: "00"
    });
  },
  saveSound() {
    var ctx = this;
    ctx.data.innerAudioContext.stop();
    wx.showToast({
      icon: "loading",
      title: "正在上传"
    });
    this.aliUpload(ctx.data.tempSound, 'voice', true)
  },
  toEditShrLng: function () {
    wx.navigateTo({
      url: "/pages/sales/look_card/edit_shrLng?id=" + this.data.cardInfo.id + "&name=" + this.data.cardInfo.name + "&shareSpeech=" + this.data.cardInfo.shareSpeech + '&headPic=' + this.data.cardInfo.headPic
    })
  },
  toEditLab: function () {
    wx.navigateTo({
      url: "/pages/sales/look_card/edit_lab?id=" + this.data.cardInfo.id
    })
  },
  aliyunUploadToken() {
    let that = this;
    wx.request({
      url: cf.config.pageDomain + '/applet/mobile/aliyunoss/getUploadToken',
      header: {
        "Content-Type": "application/json"
      },
      success: function (res) {
        that.setData({
          uploadParams: res.data.model
        })
      }
    })
  },
  showArea() {
    this.setData({
      showTextArea: true
    })
  },
  showView() {
    this.setData({
      showTextArea: false
    })
  },
  handleAliVideo() {
    var ctx = this;
    wx.chooseVideo({
      sourceType: ['album', 'camera'],
      camera: 'back',
      success(res) {
        console.log(res);
        // 20971520 20M
        // 104857600 100M
        if (104857600 < res.size) {
          wx.showToast({
            title: '视频大小不能超过100MB',
            icon: "none"
          });
          return;
        }
        ctx.aliUpload(res.tempFilePath, 'video', true);
        console.log(res.tempFilePath)
      },
      fail(e) {
        wx.showToast({
          title: '操作已取消',
          icon: "none"
        });
      }
    })
  },
  delSelfVideo() {
    var ctx = this;
    var selfVideo = wx.createVideoContext('selfVideo');
    selfVideo.stop()
    ctx.setData({
      videoUrl: ""
    });
  },
  aliUpload(tempFilePath, type = 'video', isSingle = true, e) {
    let newTempFilePath = tempFilePath
    if (tempFilePath.constructor == Array) {
      tempFilePath = tempFilePath[0]
    }
    var ctx = this;
    // wx.showLoading({
    //   title: '上传中...',
    // });
    
    let arr = tempFilePath.split('.')
    let formatFileName
    if (isSingle) {
      formatFileName = wx.getStorageSync('userId') + '.' + arr[arr.length - 1]
    } else {
      formatFileName = wx.getStorageSync('userId') + '/' + new Date().getTime() + '.' + arr[arr.length - 1]
    }
    let newFileName = `/${type}/card/${formatFileName}`;
    const a = ctx.data.uploadParams
    let newFilePath = ctx.data.uploadParams.host + "/" + a.dir + newFileName;
    ctx.reGetToken().then(upData => {
      wx.uploadFile({
        url: ctx.data.uploadParams.host,
        name: 'file',
        filePath: tempFilePath,
        header: {
          "Content-Type": "multipart/form-data"
        },
        formData: {
          OSSAccessKeyId: a.accessid,
          policy: upData.policy,
          signature: upData.signature,
          key: a.dir + newFileName,
          success_action_status: 200
        },
        success: function (res) {
          if (res.statusCode == 200) {
            if (type == 'video') {
              ctx.setData({
                videoUrl: newFilePath
              });
            } else if (type == 'image') {
              let myImg = ctx.data.myImg;
              myImg.push(newFilePath)
              ctx.setData({
                myImg
              });
            } else if (type == 'voice') {
              wx.showModal({
                title: '提示',
                content: '保存成功',
                showCancel: false
              })
              ctx.setData({
                voiceFile: newFilePath,
                recordStatus: 0,
                showVoiceModal: false,
              });
            }
            wx.hideLoading();
          } else if (res.statusCode == 403) {
            wx.hideLoading();
            if (newTempFilePath && type) {
              aliUpload(newTempFilePath, type, isSingle)
            } else {
              wx.showToast({
                title: '上传通行证过期，请重新上传并勿在图片选择界面停留过久',
                icon: 'none'
              })
            }

          } else {
            wx.hideLoading();
            wx.showToast({
              title: '上传失败，请检查网络后重新上传',
              icon: 'none'
            })
          }
        },
        fail: function (res) {
          wx.hideLoading();
          wx.showToast({
            title: '网络出错',
            icon: 'none'
          })
        }
      })
    })
  },
  handleImg() {
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        // tempFilePath可以作为img标签的src属性显示图片
        const tempFilePaths = res.tempFilePaths;
        console.log(tempFilePaths);
        wx.navigateTo({
          url: `/pages/cropper/cropper?src=${tempFilePaths[0]}&saveKey=videoImg&scaleXY=1.66`,
        })
      }
    });
  },
  delSelfVideoImg() {
    this.setData({
      videoImg: ""
    });
  },

  addCustCardStyle() {
    let ctx = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['original'],
      sourceType: ['album', 'camera'],
      success(res) {
        // tempFilePath可以作为img标签的src属性显示图片
        const tempFilePaths = res.tempFilePaths;
        wx.navigateTo({
          url: `/pages/cropper/cropper?src=${tempFilePaths[0]}&saveKey=customStyle&scaleXY=1.68&relative=y`,
        })
      }
    });
  },
  delCusCardStyle() {
    this.setData({
      customStyle: ""
    });
  },
  toPlayVideo(e) {
    var ctx = this;
    wx.navigateTo({
      url: '/pages/single_video/video_play?vUrl=' + ctx.data.videoUrl + "&isVVideo=y",
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  chooseLocation: function (e) {
    var that = this;
    wx.chooseLocation({
      success: function (res) {
        if (res.address == res.name) {
          res.name = ''
        }
        that.setData({
          locationInfo: res,
          'cardInfo.extend.address': res.address + res.name,
          'submitInfo.extend.address': res.address + res.name,
          'submitInfo.address': res.address + res.name
        })
      }
    })

  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // this.onLoad()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角
   */
  onShareAppMessage: function () {

  }
}))